﻿using Fclp;
using RunAsThisUser.ToolSet;
using System;
using System.Diagnostics;
using System.IO;
using System.Security;

namespace RunAsThisUser
{
    class Program
    {
        private static string credentialKey = null;
        private static string arguments = "";
        private static string fileName = null;

        static void Main(string[] args)
        {


            var parser = new FluentCommandLineParser();
            parser.Setup<string>('f', "file")
                .Callback(f => fileName = f)
                .WithDescription("Name of file to execute")
                .Required();

            parser.Setup<string>('a', "arguments")
                .Callback(a => arguments = a)
                .WithDescription("Arguments");

            parser.Setup<string>('c', "credentialKey")
                .Callback(c => credentialKey = c)
                .WithDescription("Encrypted credentials generated by SecureWrapperGen")
                .Required();

            parser.SetupHelp(new string[] { "h", "?", "help" })
                .UseForEmptyArgs()
                .Callback(s => Console.WriteLine(s));
            
            var results = parser.Parse(args);

           
            if (results.HasErrors)
            {
                Console.WriteLine(results.ErrorText);
                Environment.Exit(-1);
            }

            var credentialsEncrypted = File.ReadAllBytes(credentialKey);
            var credentialsDecrypted = Tools.DecryptStringFromBytes(credentialsEncrypted, Tools.PrivateKey, Tools.IVKey);
            string[] credentials = credentialsDecrypted.Split(','); //username.domain,password
           
            SecureString password = new SecureString();
            string txtPassword = credentials[2];
            foreach (var item in txtPassword)
                password.AppendChar(item);

            Process process = new Process();
            process.StartInfo.LoadUserProfile = false;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.StartInfo.UserName = credentials[0];
            process.StartInfo.Domain = credentials[1];
            process.StartInfo.Password = password;
            process.StartInfo.FileName = fileName;
            process.StartInfo.Arguments = arguments;

            try
            {
                process.Start();
            }catch(Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.ResetColor();
            }
        }
    }
}
